  // 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const uniID = require('uni-id-common')
const utils = require('uni-utils')
const uTransaction = require('uni-transaction-log')
module.exports = {
	_before: function (data) { // 通用预处理器
	   const methodName = this.getMethodName()
	   if(['get', 'add', 'update', 'delete'].includes(methodName) && !this.getUniIdToken()) {
	   	throw new Error('token不存在')
	   }
	   const clientInfo = this.getClientInfo()
	   this.uniIDIns = uniID.createInstance({ // 创建uni-id实例，其上方法同uniID
	   	clientInfo
	   })
	   this.unicloud = uniCloud.database()
	},
	/**
	 * 获取账单信息
	 * @param { number } userId 用户id required
	 * @param { number } accountId 账户id
	 * @param { string } transactionType 收入: 0 or 支出: 1
	 * @param { string } tallyTime 根据时间查询
	*/
	get(data = {}) {
		return new Promise((resolve, reject) => {
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				if('userId' in data) {
					if(data.tallyTime) {
						const date = new Date(data.tallyTime)
						const Y = date.getFullYear()
						const M = date.getMonth()
						const startTime = new Date(Y, M, 0)
						const endTime = new Date(Y, M + 1, 0)
						data.tallyTime = this.unicloud.command.gte(utils.parseTime(startTime)).and(this.unicloud.command.lte(utils.parseTime(endTime)))
					}
					return this.unicloud.collection('transaction').where({ userId: data.userId, ...data }).orderBy('tallyTime','desc').get()
				} else {
					reject({ code: 500, msg: 'userId is not empty' })
				}
			}).then(res => {
				resolve({ code: 200, data: res.data, msg: '操作成功' })
			}).catch(c => utils.captureCatch(c, resolve))
		})
	},
	/**
	 * 获取账单信息分页
	 * @param { number } userId 用户id required
	 * @param { number } accountId 账户id
	 * @param { string } transactionType 收入: 0 or 支出: 1
	 * @param { number } page 页码
	 * @param { number } size 查询数量
	 * @param { string } tallyTime 根据时间查询
	*/
	getPage(data) {
		return new Promise((resolve, reject) => {
			if(!('page' in data) || !('size' in data)) {
				return reject({ code: 500, msg: 'page || size is not empty' })
			}
			let temporary = {}
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				if('userId' in data) {
					const size = data.size === 0 ? 1 : data.size
					const page = data.page === 0 ? 1 : (data.page - 1) * size
					const obj = {}
					for (let key in data) {
						if(!['page', 'size', 'tallyTime'].includes(key)) {
							obj[key] = data[key]
						}
						if(key === 'tallyTime' && data[key]) {
							const date = new Date(data.tallyTime)
							const Y = date.getFullYear()
							const M = date.getMonth()
							const startTime = new Date(Y, M, 0).getTime()
							const endTime = new Date(Y, M + 1, 0).getTime()
							obj[key] = this.unicloud.command.gte(utils.parseTime(startTime)).and(this.unicloud.command.lte(utils.parseTime(endTime)))
						}
					}
					return this.unicloud.collection('transaction').where(obj).limit(size).skip(page).orderBy('tallyTime','desc').get()
				} else {
					reject({ code: 500, msg: 'userId is not empty' })
				}
			}).then(res => {
				temporary = res.data
				return this.unicloud.collection('transaction').where({ userId: data.userId }).get()
			})
			.then(res => {
				resolve({ code: 200, data: temporary, total: res.data.length, msg: '操作成功' })
			}).catch(c => utils.captureCatch(c, resolve))
		})
	},
	/**
	 * 添加账单信息
	 * @param { string } userId 用户id required
	 * @param { string } accountId 账户id
	 * @param { string } transactionType 收入: 0 支出: 1 还款: 2 
	 * @param { string } icon 分类名称
	 * @param { number } amount 金额
	 * @param { string } desc 备注
	 * @param { string } tallyTime 日期
	 * @param { string } meticulousTime 时间
	*/
	add(data) {
		return new Promise((resolve, reject) => {
			let _id = ''
			let accountData = {}
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				return this.unicloud.collection('account').where({ _id: data.accountId }).get()
			}).then(res => {
				if(res.data.length === 0) return Promise.reject('暂无账户!')
				data.createTime = utils.parseTime(new Date())
				accountData = res.data[0]
				if(['0', '1'].includes(data.transactionType)) {
					return this.unicloud.collection('transaction').add(data)
				} else {
					return Number(res.data[0].balance) - Number(data.amount) < 0 ? Promise.reject('余额不足!') : this.unicloud.collection('transaction').add(data)
				}
			}).then(() => {
				return utils.updateAccount(data, accountData)
			}).then(() => {
				return uTransaction.add({ method: 'POST', transactionId: _id, icon: data.icon, transactionType: data.transactionType, amount: data.amount })
			}).then(() => {
				resolve({ code: 200, msg: '操作成功' })
			}).catch(c => utils.captureCatch(c, resolve))
		})
	},
	/**
	 * 修改账单信息
	 * @param { string } _id 主键id
	 * @param { string } userId 用户id required
	 * @param { string } accountId 账户id
	 * @param { string } transactionType 收入: 0 支出: 1 还款: 2 
	 * @param { string } icon 分类名称
	 * @param { number } amount 金额
	 * @param { string } desc 备注
	 * @param { string } tallyTime 日期
	 * @param { string } meticulousTime 时间
	*/
	update(data) {
		return new Promise((resolve, reject) => {
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(() => {
				return this.unicloud.collection('account').where({ _id: data.accountId }).get()
			}).then(res => {
				if(res.data.length === 0) return Promise.reject('暂无账户!')
				return utils.updateAccount(data, res.data[0])
			}).then(res => {
				const obj = utils.excludeObject(['userId', '_id'], data)
				return this.unicloud.collection('transaction').where({ _id: data._id }).update(obj)
			}).then(res => {
				return uTransaction.add({ method: 'UPDATE', transactionId: data._id, icon: data.icon, transactionType: data.transactionType, amount: data.amount })
			}).then(res => {
				resolve({ code: 200, msg: '操作成功' })
			}).catch(c => utils.captureCatch(c, resolve))
		})
	},
	/**
	 * 删除账单信息
	 * @param { string } _id 账户Id
	*/
	delete(_id) {
		return new Promise((resolve, reject) => {
			let data = {}
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				return this.unicloud.collection('transaction').where({ _id }).get()
			}).then(res => {
				data = Object.assign({}, res.data[0])
				return this.unicloud.collection('account').where({ _id: res.data[0].accountId }).get()
			}).then(res => {
				if(res.data.length === 0) return Promise.reject('暂无账户!')
				return utils.removeAccount(data, res.data[0])
			}).then(res => {
				return this.unicloud.collection('transaction').where({ _id }).remove()
			}).then(res => {
				return uTransaction.add({ method: 'DELETE', transactionId: data._id, icon: data.icon, transactionType: data.transactionType, amount: data.amount })
			}).then(res => {
				resolve({ code: 200, msg: '操作成功' })
			}).catch(c => utils.captureCatch(c, resolve))
		})
	}
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	/* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/
}
